package com.iqiyi.pps.epg.core.service.partitions;

import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.jdbc.ConnectionDB;
import com.iqiyi.pps.epg.core.model.partition.Partition;
import com.iqiyi.pps.epg.core.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang on 2017/9/7.
 */
@Service
public class PartitionsServiceImpl implements PartitionsService {
    private static String DATABASE_NAME = Configuration.getString("dataBaseName", null);

    @Override
    public List<String> getTableNames() {
        List<String> result = new ArrayList<>();
        if (StringUtils.isNotBlank(DATABASE_NAME)) {
            String sql = "select distinct(table_name) from information_schema.partitions where table_schema = '" + DATABASE_NAME + "' and partition_name is not null;";
            ConnectionDB connectionDB = new ConnectionDB();
            List<Map<String, Object>> tableNames = connectionDB.excuteQuery(sql, null);
            for (Map<String, Object> map : tableNames) {
                String tableName = (String) map.get("table_name");
                result.add(tableName);
            }
        }
        return result;
    }

    @Override
    public List<Partition> getPartition(String name) {
        List<Partition> result = new ArrayList<>();
        if (StringUtils.isNotBlank(DATABASE_NAME)) {
            String sql = "select table_name, partition_name from information_schema.partitions where table_schema = '" + DATABASE_NAME + "' and partition_name =?;";
            ConnectionDB connectionDB = new ConnectionDB();
            Object[] params = new Object[]{name};
            List<Map<String, Object>> partitions = connectionDB.excuteQuery(sql, params);
            for (Map<String, Object> map : partitions) {
                String tableName = (String) map.get("table_name");
                String partitionName = (String) map.get("partition_name");
                Partition entity = new Partition();
                entity.setTableName(tableName);
                entity.setPartitionName(partitionName);
                result.add(entity);
            }
        }
        return result;
    }
}
